package shiro.com.controller.discuss;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.AllArgsConstructor;
import net.sf.jsqlparser.statement.select.Distinct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import shiro.com.basie.controller.BaseController;
import shiro.com.basie.domain.AjaxResult;
import shiro.com.domain.TableDataInfo;
import shiro.com.domain.discuss.Chat;
import shiro.com.domain.discuss.ChatMsg;
import shiro.com.domain.discuss.DiscussMessage;
import shiro.com.domain.sys.SysUsers;
import shiro.com.mapper.discuss.ChatMapper;
import shiro.com.mapper.discuss.ChatMsgMapper;
import shiro.com.mapper.sys.SysUsersMapper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/discuss/chat")
public class ChatController extends BaseController {
  @Autowired
  private ChatMapper chatMapper ;
  @Autowired
  private SysUsersMapper sysUsersMapper;
  @Autowired
  private ChatMsgMapper chatMsgMapper;
    @GetMapping(value = "/{id}")
    public TableDataInfo list(@PathVariable("id") Long id)
    {
        QueryWrapper<Chat> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",id);
        List<Chat> chats = chatMapper.selectList(queryWrapper);

        List<SysUsers> collect = chats.stream().map(item -> {
            int firendId = item.getFirendId();
            SysUsers sysUsers = sysUsersMapper.selectSysUsersBySysUserId((long) firendId);
            sysUsers.setSysUserPsw("");
            sysUsers.setSysUserSlat("");
            sysUsers.setSysUserAddress("");
            sysUsers.setSysUserEmail("");
            sysUsers.setSysUserPhone(0L);
            sysUsers.setSysUserNick("");
            return sysUsers;
        }).collect(Collectors.toList());
        return getDataTable(collect);
    }
    private static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
        HashMap<Object, Boolean> map = new HashMap<>();
        return t -> map.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
    }

    @GetMapping("/msg")
    public TableDataInfo listMsg(ChatMsg chatMsg){
        QueryWrapper<ChatMsg> queryWrapper = new QueryWrapper<>();


        queryWrapper.eq("user_id",chatMsg.getUserId());
        queryWrapper.eq("fre_id",chatMsg.getFreId());
        queryWrapper.or().eq("user_id",chatMsg.getFreId()).eq("fre_id",chatMsg.getUserId());

        List<ChatMsg> chats = chatMsgMapper.selectList(queryWrapper);


        return getDataTable(chats);
    }

    @PostMapping("/add")
    public AjaxResult add(@RequestBody  ChatMsg chatMsg)
    {

        int insert = chatMsgMapper.insert(chatMsg);
        return toAjax(insert);
    }

}
